package cn.javass.dp.memento.example4;


import java.util.ArrayList;
import java.util.List;

/**
 * 计算器  等于机箱
 */
public class Calculator {
    /**
     * 命令操作的撤销的历史记录
     */
    private List<Command> undoCmds = new ArrayList<>();

    /**
     * 命令操作的恢复的历史记录
     */
    private List<Command> redoCmds = new ArrayList<>();

    /**
     * 使用备忘录模式的撤销历史状态记录
     */
    private List<Memento[]> undomementos = new ArrayList<>();
    private List<Memento[]> redomementos = new ArrayList<>();



    private Command addCmd = null;
    private Command substractCmd = null;




    public void setAddCmd(Command addCmd) {
        this.addCmd = addCmd;
    }

    public void setSubstractCmd(Command substractCmd) {
        this.substractCmd = substractCmd;
    }

    public void addPressed() {
        //获取对应的备忘录对象，并保存相应的历史记录
        Memento m1 = this.addCmd.createMemento();

        this.addCmd.execute();
        undoCmds.add(this.addCmd);

        Memento m2 = this.addCmd.createMemento();

        //设置到撤销的历史记录里面
        this.undomementos.add(new Memento[]{m1, m2});
    }

    public void substractPressed() {

        //获取对应的备忘录对象，并保存相应的历史记录
        Memento m1 = this.addCmd.createMemento();

        this.substractCmd.execute();
        undoCmds.add(substractCmd);

        //设置到撤销的历史记录里面
        Memento m2 = this.addCmd.createMemento();
        this.undomementos.add(new Memento[]{m1, m2});
    }


    public void undoPressed() {
        if (undoCmds.size() > 0) {
            Command cmd = undoCmds.get(undoCmds.size()-1);
/*
            cmd.undo();
*/
            //获取对应的备忘录对象
            Memento[] ms = undomementos.get(undoCmds.size()-1);

            //撤销
            cmd.undo(ms[0]);

            redomementos.add(ms);
            undomementos.remove(ms);
            this.redoCmds.add(cmd);
            this.undoCmds.remove(cmd);

        } else {
            System.out.println("没有可以撤销的操作");
        }
    }

    public void redoPressed() {
        if (redoCmds.size() > 0) {
            Command cmd = redoCmds.get(redoCmds.size()-1);

            //获取对应的备忘录对象
            Memento[] ms = redomementos.get(undoCmds.size()-1);

            //撤销
            cmd.redo(ms[1]);

            redomementos.remove(ms);
            undomementos.add(ms);

           /* cmd.execute(); //这里不是undo 是重新运算*/
            this.undoCmds.add(cmd);
            this.redoCmds.remove(cmd);

        } else {
            System.out.println("没有可以恢复的操作");
        }
    }
}
